const modulesFiles = require.context('./modules', true, /\.js$/);

const modules = modulesFiles.keys().reduce((modules, modulePath) => {
	const value = modulesFiles(modulePath);
	modules = [...modules, value.default];
	return modules;
}, []);

const menusDataSource = (arr) => {
	return arr.map((item) => {
		const currentMenu = {
			...item.meta,
			key: item.redirect || item.path,
			label: item.meta?.title
		};
		if (item.children && item.children.length > 0) {
			currentMenu.children = menusDataSource(item.children);
		}
		return currentMenu;
	});
};

const filterMenu = (menuList) => {
	return menuList
		.filter((item) => {
			return !item.hideMenu;
		})
		.map((item) => {
			item = Object.assign({}, item);
			if (item.children) {
				item.children = filterMenu(item.children);
			}
			return item;
		});
};

const transformMenuModule = (menu) => {
	if (menu.children && menu.children.length > 0) {
		menu.children = filterMenu(menu.children);
	}
	if (menu.hideChildrenInMenu && menu.children) {
		delete menu.children;
	}
	return menu;
};

const staticMenus = [];
(() => {
	// 菜单排序
	modules.sort((a, b) => {
		return (a.meta.orderNo || 0) - (b.meta.orderNo || 0);
	});
	const getMenus = menusDataSource(modules);
	for (const menu of getMenus) {
		staticMenus.push(transformMenuModule(menu));
	}
})();

export default staticMenus;
